package com.hllxd.hism.passport.base.redis;

import com.hllxd.hism.passport.base.config.redis.PassportClientRedisAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @program: hllopen-rbac
 * @author: yuanhao
 * @description:
 * @create: 2020-05-12 11:29
 */
@Slf4j
@Service("accessTokenRedisMapper")
public class AccessTokenRedisMapperImpl implements AccessTokenRedisMapper {
  @Autowired private PassportClientRedisAdapter redisAdapter;

  // 有效时间30天
  private static final long EXPIRE_DATE = 30 * 24 * 60 * 60 * 1000L;

  // MIS TOKEN 前缀
  private static final String MIS_TOKEN_PREFIX = "inward_hllopen_token:";
  private static final String MIS_TOKEN_INFO_PREFIX = "inward_hllopen_token_i:";

  // 拼接命名空间前缀
  private String buildKey(String openID, String appKey, String appSecret) {
    return MIS_TOKEN_PREFIX + openID + "^" + appKey + "^" + appSecret;
  }

  private String buildKey2(String key) {
    return MIS_TOKEN_INFO_PREFIX + key;
  }

  @Override
  public String getAccessToken(String openID, String appKey, String appSecret) {
    return redisAdapter.getValue(buildKey(openID, appKey, appSecret));
  }

  @Override
  public void setAccessToken(String openID, String appKey, String value, String appSecret) {

    redisAdapter.setValue(buildKey(openID, appKey, appSecret), value, EXPIRE_DATE);
  }

  @Override
  public boolean isTokenExist(String token) {
    String result = redisAdapter.getValue(buildKey2(token));
    return null != result;
  }

  @Override
  public void setTokenInfo(String token, String value) {

    redisAdapter.setValue(buildKey2(token), value, EXPIRE_DATE);
  }

  @Override
  public String getTokenInfo(String token) {
    log.info("get token params: {}.", token);
    return redisAdapter.getValue(buildKey2(token));
  }
}
